<?php
class UserController{

	function findAll(){
		$objDB = $GLOBALS['objDB'];
		$rsU = $objDB->Execute("SELECT * FROM users ;");
		while(!$rsU->EOF){
			$user = new User($rsU->fields['USERNAME'],$rsU->fields['PASSWORD'],$rsU->fields['NAME']);
			$users[]= $user;
			$rsU->MoveNext();
		}
		return $users;
	}
	
	function save($u){
		$objDB = $GLOBALS['objDB'];
		$rsU = $objDB->Execute("SELECT * FROM users WHERE USERNAME='-1';");
		$arrRecords['USERNAME']=$u->username;
		$arrRecords['PASSWORD']=$u->password;
		$arrRecords['NAME']    =$u->name;
		$strInserSql = $objDB->GetInsertSQL($rsU,$arrRecords);
		$objDB->Execute($strInserSql); 
		return true;
	}
	function update($u){
		$objDB = $GLOBALS['objDB'];
		$objDB->Execute("UPDATE users SET NAME='$u->name' WHERE USERNAME='$u->username' ;");
		return true;
	}
	
	function delete($id){
		$objDB = $GLOBALS['objDB'];
		$objDB->Execute("DELETE FROM users WHERE USERNAME='$id' ;");		
		return true;
	}
	
	function saveRoles($u ,$uroles){
		$objDB = $GLOBALS['objDB'];
		foreach ($uroles as $rid){
			$objDB->Execute("INSERT INTO user_roles VALUES('$u->username','$rid') ;");
		}
	}
	
	function findId($u) {
		$objDB = $GLOBALS['objDB'];
		$rsU = $objDB->Execute("SELECT * FROM users WHERE USERNAME='$u->username' ;");
		$user = new User($rsU->fields['USERNAME'],$rsU->fields['PASSWORD'],$rsU->fields['NAME']);
		return $user;
	}
	
	function findAllRoles(){
		return RoleController::findAll();
	}
	
	function find($id){
		$objDB = $GLOBALS['objDB'];
		$rsU = $objDB->Execute("SELECT * FROM users WHERE USERNAME='$id' ;");
		if (!$rsU->EOF){
			$user = new User($rsU->fields['USERNAME'],$rsU->fields['PASSWORD'],$rsU->fields['NAME']);
		}else{
			$user = new User("guest","","Guest");
		}
		return $user;
	}
	
	function findRoleIds($id){
		$objDB = $GLOBALS['objDB'];
		$rsRID = $objDB->Execute("SELECT RID FROM user_roles WHERE UID='$id' ;");
		$rids = array();
		while(!$rsRID->EOF){
			$rids[] = $rsRID->fields['RID'];
			$rsRID->MoveNext();			
		}		
		return $rids;
	}

	function deleteRoles($id){
		$objDB = $GLOBALS['objDB'];
		$objDB->Execute("DELETE FROM user_roles WHERE UID='$id' ;");
		return true;
	}
	

	function updatep($u){
		$objDB = $GLOBALS['objDB'];
		$objDB->Execute("UPDATE users SET PASSWORD='$u->password' WHERE USERNAME='$u->username' ;");
		return true;
	}
	
	
	function findUserRoles($user){
		$roles = UserController::findRoleIds($user->username);
		foreach ($roles as $role) {
			$user->addToRoles($role);			
		}
		return $user;
	}
}
?>